import { Reducer } from 'redux';
import { Effect } from 'dva';

import { costAdd, costList, costDelete, costEdit } from '@/services/cost';
import { notification } from 'antd';

export interface StateType {
  isRefresh?: boolean;
  total?: number;
  view?: any;
  edit?: any;
  list?: any;
}

export interface LoginModelType {
  namespace: string;
  state: StateType;
  effects: {
    view: Effect;
    add: Effect;
    edit: Effect;
    delete: Effect;
    list: Effect;
  };
  reducers: {
    redView: Reducer<StateType>;
    redEdit: Reducer<StateType>;
    redList: Reducer<StateType>;
    reFresh: Reducer<StateType>;
  };
}

const Model: LoginModelType = {
  namespace: 'cost',

  state: {
    total: 0,
    isRefresh: false,
    list: [],
    view: {},
    edit: {},
  },

  effects: {
    *add({ payload }, { call, put }) {
      const res = yield call(costAdd, payload);
      if (res.status == 200) {
        notification.success({
          message: '新增成功',
          description: '',
        });
        yield put({
          type: 'reFresh',
          payload: true,
        });
      }
    },
    *view({ payload }, { call, put }) {
      yield put({
        type: 'redView',
        payload,
      });
    },
    *edit({ payload }, { call, put }) {
      const res = yield call(costEdit, payload);
      if (res.status == 200) {
        notification.success({
          message: '修改成功',
          description: '',
        });
        yield put({
          type: 'reFresh',
          payload: true,
        });
      }
    },
    *delete({ payload }, { call, put }) {
      const res = yield call(costDelete, payload);
      if (res.status == 200) {
        notification.success({
          message: '删除成功',
          description: '',
        });
        yield put({
          type: 'reFresh',
          payload: true,
        });
      }
    },
    *list({ payload }, { call, put }) {
      const res = yield call(costList, payload);
      if (res.status == 200) {
        yield put({
          type: 'redList',
          payload: { data: res.data.content, total: res.data.totalElements },
        });
      }
    },
  },

  reducers: {
    redView(state, { payload }) {
      return {
        ...state,
        view: payload,
      };
    },
    redEdit(state, { payload }) {
      return {
        ...state,
        edit: payload,
      };
    },
    redList(state, { payload }) {
      return {
        ...state,
        list: payload.data,
        total: payload.total,
        isRefresh: false,
      };
    },
    reFresh(state, { payload }) {
      return {
        ...state,
        isRefresh: payload,
      };
    },
  },
};

export default Model;
